package com.bi.design.mqtt.borker.protocol;

import com.bi.design.mqtt.borker.store.session.ISessionStoreService;
import com.bi.design.mqtt.borker.store.session.SessionStore;
import com.bi.design.mqtt.borker.store.subscribe.ISubscribeStoreService;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;


/**
 * DISCONNECT连接处理
 */
@Slf4j
public class DisConnect {
    private ISessionStoreService sessionStoreService;

    private ISubscribeStoreService subscribeStoreService;


    public DisConnect(ISessionStoreService sessionStoreService, ISubscribeStoreService subscribeStoreService) {
        this.sessionStoreService = sessionStoreService;
        this.subscribeStoreService = subscribeStoreService;
    }
    public void processDisConnect(Channel channel, MqttMessage msg) {
        String clientId = (String) channel.attr(AttributeKey.valueOf("clientId")).get();
        SessionStore sessionStore = sessionStoreService.get(clientId);
        if (sessionStore != null && sessionStore.isCleanSession()) {
            subscribeStoreService.removeForClient(clientId);
        }
        log.info("DISCONNECT - clientId: {}, cleanSession: {}", clientId, sessionStore.isCleanSession());
        sessionStoreService.remove(clientId);
        channel.close();
    }

}
